<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        clearable
        placeholder="标题"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
      />
      <el-input
        v-model="listQuery.keyword"
        clearable
        placeholder="关键字"
        style="width: 200px"
        class="filter-item"
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
      />
      <el-select
        v-model="listQuery.category_id"
        clearable
        placeholder="所属分类"
        style="width: 130px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option v-for="(item, index) in categoryOptions" :key="'shop_product_list' + index" :value="item.id" :label="item.title" />
      </el-select>
      <el-select
        v-model="listQuery.virtual_product"
        clearable
        placeholder="是否为虚拟商品"
        style="width: 130px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option :value="0" label="非虚拟商品" />
        <el-option :value="1" label="虚拟商品" />
      </el-select>
      <!-- <span>
        价格：
        <el-slider
          v-model="listQuery.sales_volume"
          style="width: 400px"
          class="filter-item"
          label="价格"
          :min="0"
          :max="10000"
          :range="true"
          @change="handleFilter"
        />
      </span> -->
      <el-button
        v-waves
        style="margin-left: 10px"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-circle-plus-outline"
        @click="handleAdd"
      >
        新增
      </el-button>
      <el-button
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        @click="handleDelete(0)"
      >
        批量删除
      </el-button>
    </div>

    <el-table
      ref="itemDataTable"
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;margin-top: 20px"
      @sort-change="tableSortChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="ID"
        prop="id"
        align="center"
        width="80"
      />
      <el-table-column label="标题" width="200" align="center">
        <template slot-scope="{ row: { titleWrapper }}">
          <span v-html="titleWrapper" />
        </template>
      </el-table-column>
      <el-table-column label="主图" width="120" align="center">
        <template slot-scope="{ row: { main_image: { prefix } }}">
          <img
            v-if="prefix.length === 0"
            style="width: 90px"
            src="@/assets/static/image/noImg.png"
          >
          <a v-else :href="prefix[0]" target="_blank">
            <img
              :src="prefix[0]"
              style="width: 90px"
            >
          </a>
        </template>
      </el-table-column>
      <el-table-column
        label="销量"
        prop="sales_volume"
        sortable="custom"
        align="center"
        width="120"
      >
        <template slot-scope="{ row }">
          {{ row.sales_volume }}({{ row.virtual_sales_volume }})
        </template>
      </el-table-column>
      <el-table-column label="商品规格" align="center">
        <template slot-scope="{ row: { specs }}">
          <el-row v-for="(specs_item, specs_index) in specs" :key="'list_specs' + specs_index">
            <el-col :span="24">
              ({{ specs_item.id }})
              <span v-for="(specs_prop_item, specs_prop_index) in specs_item.property" :key="'list_specs_prop' + specs_prop_index">
                {{ specs_prop_item.property.name + ':' + specs_prop_item.value + ' | ' }}
              </span>
              {{ specs_item.original_price + ' | ' +
                specs_item.selling_price + ' | ' +
                specs_item.stock
              }}
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="所属分类" width="120" align="center">
        <template slot-scope="{ row: { category }}">
          <span>{{ category.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" width="120">
        <template slot-scope="{ row }">
          <el-input-number
            v-model="row.sort"
            controls-position="right"
            style="width: 100%"
            @change="handleContentSort($event, row.id)"
          />
        </template>
      </el-table-column>
      <el-table-column label="推荐" width="100" align="center">
        <template slot-scope="{ row }">
          <it-switch
            v-model="row.recomm"
            :active-value="1"
            :inactive-value="0"
            active-text="推荐"
            inactive-text="关闭"
            @change="handleContentStatus($event, row.id, 'recomm')"
          />
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{ row }">
          <it-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            active-text="开启"
            inactive-text="停用"
            @change="handleContentStatus($event, row.id, 'status')"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="{ row: { id } }">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(id)">编辑</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="handleFilter"
    />

    <!-- 添加/编辑弹出框 -->
    <el-dialog
      :title="detailEditID !== 0 ? '编辑商品信息' : '添加商品信息'"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      top="5vh"
      width="80%"
      @close="closeDialog"
    >
      <shop-product-detail v-if="dialogFormVisible" :id="detailEditID" ref="shopProductDetail" @ended="handleSubmitEnd" />
    </el-dialog>

  </div>
</template>

<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import TnInnerTextSwitch from '@/components/TNInnerTextSwitch'
import ShopProductDetail from '../components/product/Detail'
import { wrapperKeyword } from '@/utils'
import { getAllCategoryTitle } from '@/api/shop-category'
import { getProductList, updateProduct, deleteProduct } from '@/api/shop-product'

export default {
  name: 'ShopProductList',
  components: { Pagination, 'it-switch': TnInnerTextSwitch, ShopProductDetail },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      listLoading: false,
      total: 0,
      categoryOptions: [],
      listQuery: {
        page: 1,
        limit: 20,
        title: '',
        keyword: '',
        category_id: '',
        virtual_product: '',
        sales_volume: [0, 10000]
      },
      list: [],
      detailEditID: 0,
      dialogFormVisible: false
    }
  },
  watch: {
    list(val) {
      val.forEach(product => {
        const virtual_text = product.virtual_product ? '|虚拟' : ''
        product.titleWrapper = wrapperKeyword(this.listQuery['title'] || '', product.title + virtual_text)
      })
    }
  },
  mounted() {
    this.getCategoryAllTitle()
    this.getList()
  },
  methods: {
    handleFilter() {
      this.getList()
    },
    handleAdd() {
      this.detailEditID = 0
      this.dialogFormVisible = true
      this.$nextTick().then(() => {
        this.$refs.shopProductDetail.getAllCategoryTitle()
      })
    },
    handleEdit(id) {
      this.detailEditID = id
      this.dialogFormVisible = true
      this.$nextTick().then(() => {
        this.$refs.shopProductDetail.getAllCategoryTitle()
      })
    },
    handleDelete(id) {
      this.$confirm('此操作将永久删除该数据，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        // 判断是否为批量删除
        if (id === 0) {
          const _selection = this.$refs.itemDataTable.selection
          // console.log(_selection)
          if (_selection.length === 0) {
            this.$message({
              message: '请选择需要删除的数据',
              type: 'error'
            })
            return
          }
          _selection.forEach((value, index) => {
            ids.push(value.id)
          })
        } else {
          ids.push(id)
        }

        // console.log(ids)

        deleteProduct(ids).then(response => {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.getList()
        })
      }).catch(() => {})
    },
    handleContentSort(value, id) {
      // console.log(id, value)
      updateProduct({
        id,
        field: 'sort',
        value
      }).then(response => {
        this.$message({
          message: response.msg,
          type: 'success',
          duration: 2000
        })
      })
    },
    handleContentStatus(value, id, field) {
      updateProduct({
        id,
        field,
        value
      }).then(response => {
        this.$message({
          message: response.msg,
          type: 'success',
          duration: 2000
        })
      })
    },
    closeDialog() {
      this.$refs.shopProductDetail.toDefault()
      this.detailEditID = 0
    },
    handleSubmitEnd() {
      this.dialogFormVisible = false
      this.getList()
    },
    tableSortChange(data) {
      const { prop, order } = data
      // console.log(prop, order, data)
      this.listQuery.sort_prop = prop
      this.listQuery.sort_order = order
      this.getList()
    },
    getList() {
      this.listLoading = true
      getProductList(this.listQuery).then(response => {
        const {
          total,
          data
        } = response
        this.total = total
        this.list = data
        this.listLoading = false
      })
    },
    getCategoryAllTitle() {
      getAllCategoryTitle().then((response) => {
        this.categoryOptions = response.data
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>

